package com.qinsong.myapplication.model.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.qinsong.myapplication.model.bean.UserInfo;
import com.qinsong.myapplication.model.db.UserAccountDB;

/**
 * 用户持久化操作
 */
public class UserAccountDao {
    private final UserAccountDB userAccountDB;

    public UserAccountDao(Context context) {
        userAccountDB = new UserAccountDB(context);
    }
    //添加用户信息到数据库
    public void addUser(UserInfo user){
        //获取数据库对象
        SQLiteDatabase db = userAccountDB.getReadableDatabase();
        //执行添加操作
        //封装进用户信息bean
        ContentValues values = new ContentValues();
        values.put(UserAccountTable.COL_HXID,user.getHxid());
        values.put(UserAccountTable.COL_NAME,user.getName());
        values.put(UserAccountTable.COL_NICHEN,user.getNichen());
        values.put(UserAccountTable.COL_PHOTO,user.getPhoto());

        db.replace(UserAccountTable.TAB_NAME,null,values);

    }
    //根据环信id获取用户信息
    public UserInfo getUserInfoByHxId(String hxId){
        //获取数据库对象
        SQLiteDatabase db = userAccountDB.getReadableDatabase();

        //执行查询语句
        String sql="select * from " + UserAccountTable.TAB_NAME + " where " + UserAccountTable.COL_HXID + "=?";
        Cursor cursor = db.rawQuery(sql,new String[]{hxId});
        UserInfo userInfo=null;
        if (cursor.moveToNext()){
            userInfo = new UserInfo();
            //对应列名
            userInfo.setHxid(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_HXID)));
            userInfo.setName(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_NAME)));
            userInfo.setNichen(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_NICHEN)));
            userInfo.setPhoto(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_PHOTO)));
        }
        //关闭资源
        cursor.close();
        //返回数据
        return userInfo;
    }
}
